#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from apps.common import execute_time
from apps.news.control import create_and_update_news
from init_extends.init_extends import scheduler
from utils.log_utils import get_logger

logger = get_logger(__name__)


@execute_time
def async_create_news_info(app):
    """ 创建新闻记录 """
    with app.app_context():
        logger.info(">>>>>>>>>>>> starting")
        create_and_update_news()
        logger.info("<<<<<<<<<<<< end")


def scheduler_spider_news(app):
    logger.info("【scheduler】>>>>>>>>>>>> starting")
    with app.app_context():
        create_and_update_news()
    logger.info("【scheduler】<<<<<<<<<<<< end")


def register_scheduler(app):
    """ 注册定时任务 """
    jobs = [
        # 例如
        {
            'id': 'scheduler_spider_news',  # 任务id
            'func': scheduler_spider_news,  # 执行任务的函数
            'args': (app,),  # 定时任务参数
            'trigger': 'interval',  # 定时任务类型
            'seconds': 60 * 10,  # 间隔时间
            'replace_existing': True  # 若已经存在任务是否替换
        }
    ]

    for j in jobs:
        scheduler.add_job(**j)

